package com.yjd.bi.interceptor;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yjd.comm.system.dto.AdminDataWrap;
import com.yjd.comm.system.util.AdminDataUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.TxtFileCacheUtil;
import com.yjd.comm.vo.Constant.ResultEnum;

/**
 * @ClassName: LoginInterceptor
 * @Description: 登陆验证
 * @author ready likun_557@163.com
 * @date 2014-8-19 下午2:16:14
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
	private static String NO_LOGIN_URL_FILE = "nologinurl.txt";

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (urlIsNeedValidate(ServletUtil
				.getRquestUriNotContainContextPath(request))) {
			// 将用户关联的权限菜单编码放入到request中
			AdminDataWrap adminDataWrap = AdminDataUtil.getAdminDataWrap(
					request, response);
			if (adminDataWrap == null) {
				FrameUtil.throwBaseException4(ResultEnum.ERROR, null,
						ServletUtil.getRootPath(), "请登录!");
				return false;
			}
		}
		return true;
	}

	/**
	 * @Title: urlIsNeedValidate
	 * @Description: 判断url是否需要验证
	 * @param @param requestUrl
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	private boolean urlIsNeedValidate(String requestUrl) {
		List<String> list = TxtFileCacheUtil.get(NO_LOGIN_URL_FILE);
		if (list != null) {
			for (String string : list) {
				Pattern pattern = Pattern.compile(string);
				Matcher matcher = pattern.matcher(requestUrl);
				boolean b = matcher.matches();
				if (b) {
					return false;
				}
			}
		}
		return true;
	}

}
